package id.co.rho.scoring.cid.server.dao.impl;

import id.co.rho.scoring.cid.domain.Criteria;
import id.co.rho.scoring.cid.domain.Model;
import id.co.rho.scoring.cid.server.dao.CriteriaDao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Component;

@Component
public class CriteriaDaoImpl implements CriteriaDao {
	@PersistenceContext
	EntityManager entityManager;

	@Override
	public List<Criteria> getAllCriteria() {
		return entityManager.createQuery("from Criteria").getResultList();
	}

	@Override
	public List<Criteria> getCriteriaByParent(Long parentId) {
		return entityManager
				.createQuery("from Criteria where parent.id= :parentId")
				.setParameter("parentId", parentId).getResultList();
	}

	@Override
	public String setAsDefault(Long id, String modelName) {
		int count = entityManager
				.createQuery(
						"Update Model m set m.aktifStatus=:status where lower(m.modelName) =:modelName")
				.setParameter("status", Boolean.FALSE)
				.setParameter("modelName", modelName.toLowerCase())
				.executeUpdate();

		count = entityManager
				.createQuery(
						"Update Model m set m.aktifStatus=:status where m.id =:id")
				.setParameter("status", Boolean.TRUE).setParameter("id", id)
				.executeUpdate();

		return String.valueOf(count);
	}

	@Override
	public Integer findModelByName(String modelName) {
		List<Model> models = new ArrayList<Model>();
		models = entityManager
				.createQuery(
						"from Model m where lower(m.modelName) =:modelName")
				.setParameter("modelName", modelName.toLowerCase())
				.getResultList();

		return models.size();
	}
	
	@Override
	public Integer getModelRev(String modelName) {
		String res = entityManager
				.createQuery("select max(revision) as rev from Model where modelName= :modelName")
				.setParameter("modelName", modelName)
				.getSingleResult().toString();
		return Integer.valueOf(res)+1;
	}

}
